﻿/*
Author: MBH
DateAuthored: 8/11/09  
*/

//Module that adds a button to a liteGrid toolbar for adding new rows to a table. 
function RowAdditionModule() {

	var base = this;

	//The negative incremental ID assigned to new rows when they are added.
	var rowId = -1;

	//Registers for the post-init event so that buttons can be added to the toolbar.
	base.initialize = function(liteGrid, options) {

		base.liteGrid = liteGrid;
		base.options = options;

		liteGrid.$el.bind("initializationComplete", function() {
			//Make sure the toolbar module exists.  If not, this module can't be used. 
			if (!base.liteGrid.addToolbarButton) {
				console.error("RowAdditionModule requires ToolbarModule.  Be sure the module is initialized correctly.");
				return;
			}

			base.createButton();
		});
	}

	//Creates a button that will add a new blank row to the grid.
	base.createButton = function() {

		base.liteGrid.addToolbarButton({ icon: "ui-icon-plus", text: "Add",
			action: function() {
				//Build a data item with no values but the row ID.  It has to have at least that value.
				var dataItem = {};
				dataItem[base.options.rowIdColumn] = rowId--;

				//Tag the row so that we know it isn't saved to the server yet
				dataItem.IsNewRow = true;

				var row = base.liteGrid.appendRow(dataItem);

				//Make sure the row is visible
				base.liteGrid.bodyDiv.attr("scrollTop", base.liteGrid.bodyDiv.attr("scrollHeight"))

				//Mark the row as modified.
				row.children("td").addClass("modified ui-state-highlight");

				var rowAddedEvent = $.Event("rowAdded");
				rowAddedEvent.row = row;
				base.liteGrid.$el.trigger(rowAddedEvent);
			}
		});
	}
}